package br.com.affero.action;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import br.com.affero.bean.Document;
import br.com.affero.bean.User;
import br.com.affero.facade.DomainFacade;
import br.com.affero.form.DocumentForm;
import br.com.affero.util.UploadedFile;

/**
 * Action para inserção de documentos.
 * 
 * @author Marcus Henrique <marcushbarbosa@gmail.com>
 */
public class NewDocumentAction extends Action {
	
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		if (request.getMethod().equalsIgnoreCase("post")) {
			if (form instanceof DocumentForm) {
				DocumentForm documentForm = (DocumentForm) form;				
				Document document = new Document();
				
				// Setando dados da entidade.
				BeanUtils.copyProperties(document, documentForm);				
				document.setUploadDate(new Date());
				
				String filePath = UploadedFile.save(getServlet().getServletContext(), documentForm.getFile(), "documents");
				document.setFilePath(filePath);
				
				// Obtendo usuário "logado" dono do documento.
				User user = (User) request.getSession().getAttribute("user");			
				DomainFacade.getInstance().insertDocument(document, user);
				
				return mapping.findForward("list");
			}
			
			return null;
		}

		request.setAttribute("document", new Document());
		return mapping.findForward("formNew");
	}
	
}
